<template>
  <view v-if="!isFirstload" class="container" :style="appThemeStyle">
    <!-- 页面头部 -->
    <view class="main-header" :style="{ paddingTop: platform == 'H5' ? '0' : '80rpx' }">
		<image src="/static/img/user-bg.jpg" class="user-bg-item" mode="aspectFill"></image>
      <!-- 用户信息 -->
      <view v-if="isLogin" class="user-info">
		<view class="user-avatar" @click="handlePersonal()">
		    <avatar-image :url="getImgUrl(userInfo.avatar)" :width="120" v-if="userInfo.avatar && userInfo.avatar != 'def-avatar.png'" />
			<image src="/static/def-avatar.png" class="user--avatar-item" mode="scaleToFill" v-else></image>
		</view>
        <view class="user-content">
          <!-- 会员昵称 -->
          <view class="nick-name oneline-hide" @click="handlePersonal()">
		     {{ userInfo.nick_name }} 
			 <image class="image-cc" src="/static/male.png" mode="scaleToFill" v-if="userInfo.gender == 1"></image>
		     <image class="image-cc" src="/static/female.png" mode="scaleToFill" v-else-if="userInfo.gender == 2"></image>
		  </view>
          <!-- 会员无等级时显示手机号 -->
          <view class="other--info">
			  <view class="mobile" v-if="userInfo.mobile">手机号：{{ maskPhoneNumber(userInfo.mobile) }}</view>
		  </view>
		  <view class="other--info" v-if="userInfo.status">
			  <view class="identity">会员到期：{{formatTime(userInfo.status)}}</view>
		  </view>
		  <view class="other--info" v-else>
			  <view class="identity">会员已过期</view>
		  </view>
        </view>
      </view>
      <!-- 未登录 -->
      <view v-else class="user-info" @click="handleLogin">
		  <view class="user-avatar">
		    <avatar-image :width="100" />
		  </view>
        <view class="user-content">
          <view class="nick-name">未登录</view>
          <view class="login-tips">点击登录账号</view>
        </view>
      </view>
    </view>
    <view class="user--list i-card" @click="goCourseRecord()">
		<view class="user--item">
			<view>
				 <image class="user-item-image" src="/static/user/course.png" mode="scaleToFill"></image>
				<text>我观看过的课程</text>
			</view>
			<uni-icons type="right" size="16" class="user--icon-s"></uni-icons>
		</view>
	</view>
<!--	<view class="user--list i-card">
		<view class="user--item">
			<view>
				 <image class="user-item-image" src="/static/user/live.png" mode="scaleToFill"></image>
				<text>我观看过的直播</text>
			</view>
			<uni-icons type="right" size="16" class="user--icon-s"></uni-icons>
		</view>
	</view> -->
	<view class="user--list i-card" @click="goHomeworkManage()">
		<view class="user--item">
			<view>
				<image class="user-item-image" src="/static/user/privacyPolicy.png" mode="scaleToFill"></image>
				<text>作业管理</text>
			</view>
			<uni-icons type="right" size="16" class="user--icon-s"></uni-icons>
		</view>
	</view>
	<view class="user--list i-card">
		<view class="user--item">
			<view>
				 <image class="user-item-image" src="/static/user/advertise.png" mode="scaleToFill"></image>
				<text>看广告挣钱</text>
			</view>
			<uni-icons type="right" size="16" class="user--icon-s"></uni-icons>
		</view>
	</view>
<!-- 	<view class="user--list i-card" @click="goAboutUsDetails()">
		<view class="user--item">
			<view>
				<image class="user-item-image" src="/static/user/aboutUs.png" mode="scaleToFill"></image>
				<text>关于我们</text>
			</view>
			<uni-icons type="right" size="16" class="user--icon-s"></uni-icons>
		</view>
	</view> -->
	<view class="user--list i-card" @click="goDetails()">
		<view class="user--item">
			<view>
				 <image class="user-item-image" src="/static/user/privacyPolicy.png" mode="scaleToFill"></image>
				<text>隐私协议</text>
			</view>
			<uni-icons type="right" size="16" class="user--icon-s"></uni-icons>
		</view>
	</view>
	<!-- <view class="user--list i-card" v-for="(item, index) in agreement_list" :key="index" @click="goDetails(item.id)">
		<view class="user--item">
			<view>
				 <image class="user-item-image" src="/static/user/privacyPolicy.png" mode="scaleToFill"></image>
				<text>{{item.title}}</text>
			</view>
			<uni-icons type="right" size="16" class="user--icon-s"></uni-icons>
		</view>
	</view> -->
    <!-- 绑定手机号 -->
 <!--   <view v-if="isLogin && !userInfo.mobile && setting[SettingKeyEnum.REGISTER.value].isManualBind" class="my-mobile"
      @click="handleBindMobile()">
      <view class="info">点击绑定手机号，确保账户安全</view>
      <view class="btn-bind">去绑定</view>
    </view> -->

    <!-- 退出登录 -->
    <view v-if="isLogin" class="my-logout">
      <view class="logout-btn" @click="handleLogout()">
        <text>退出登录</text>
      </view>
    </view>

  </view>
</template>

<script>
  import store from '@/store'
  import { inArray, ImgUrlPrefix, timestampChangDate } from '@/utils/util'
  import AvatarImage from '@/components/avatar-image'
  import CustomerBtn from '@/components/customer-btn'
  import { setCartTabBadge } from '@/core/app'
  import SettingKeyEnum from '@/common/enum/setting/Key'
  import StoreModel from '@/common/model/Store'
  import SettingModel from '@/common/model/Setting'
  import * as UserApi from '@/api/user'
  import * as OrderApi from '@/api/order'
  import * as homeworkApi from '@/api/homework'
  import { checkLogin, filterModules } from '@/core/app'
  import { USER_ID, NICK_NAME, STATUS } from '@/store/mutation-types'
  import storage from '@/utils/storage'
  // 订单操作
  const orderNavbar = [
    { id: 'all', name: '全部订单', icon: 'qpdingdan' },
    { id: 'payment', name: '待支付', icon: 'daifukuan', count: 0 },
    { id: 'delivery', name: '待发货', icon: 'daifahuo', count: 0 },
    { id: 'received', name: '待收货', icon: 'daishouhuo', count: 0 },
  ]

  /**
   * 我的服务
   * id: 标识; name: 标题名称; icon: 图标; type 类型(link和button); url: 跳转的链接
   */
  const service = [
    { id: 'address', name: '收货地址', icon: 'shouhuodizhi', type: 'link', url: 'pages/address/index' },
    { id: 'coupon', name: '领券中心', icon: 'lingquan', type: 'link', url: 'pages/coupon/index', moduleKey: 'market-coupon' },
    { id: 'myCoupon', name: '优惠券', icon: 'youhuiquan', type: 'link', url: 'pages/my-coupon/index', moduleKey: 'market-coupon' },
    { id: 'refund', name: '退换/售后', icon: 'shouhou', type: 'link', url: 'pages/refund/index', count: 0 },
    { id: 'contact', name: '在线客服', icon: 'kefu', type: 'contact' },
    { id: 'points', name: '我的积分', icon: 'jifen', type: 'link', url: 'pages/points/log', moduleKey: 'market-points' },
    { id: 'orderCenter', name: '订单中心', icon: 'order-c', type: 'link', url: 'pages/order/center' },
    { id: 'help', name: '我的帮助', icon: 'bangzhu', type: 'link', url: 'pages/help/index', moduleKey: 'content-help' },
  ]

  export default {
    components: {
      AvatarImage,
      CustomerBtn
    },
    data() {
      return {
        inArray,
        // 枚举类
        SettingKeyEnum,
        // 正在加载
        isLoading: true,
        // 首次加载
        isFirstload: true,
        // 是否已登录
        isLogin: false,
        // 系统设置
        setting: {},
        // 当前用户信息
        userInfo: {
			mobile:''
		},
        // 账户资产
        assets: { balance: '--', points: '--', coupon: '--' },
        // 我的服务
        service,
        // 订单操作
        orderNavbar,
        // 当前用户待处理的订单数量
        todoCounts: { payment: 0, deliver: 0, received: 0 }
      }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onLoad(options) {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      this.onRefreshPage()
    },

    methods: {

      // 刷新页面
      onRefreshPage() {
        // 更新购物车角标
        // setCartTabBadge()
        // 判断是否已登录
        this.isLogin = checkLogin()
		console.log(this.isLogin,'user')
		this.isFirstload = false
        // 获取页面数据
        this.getPageData()
      },

      // 获取页面数据
      getPageData(callback) {
        const app = this
        app.isLoading = true
        Promise.all([app.getUserInfo()])
          .then(result => {
            app.isFirstload = false
            // // 初始化我的服务数据
            // app.initService()
            // // 初始化订单操作数据
            // app.initOrderTabbar()
            // 执行回调函数
            callback && callback()
          })
          .catch(err => console.log('catch', err))
          .finally(() => app.isLoading = false)
      },

      // 初始化我的服务数据
      async initService() {
        const app = this
        const isShowCustomerBtn = await SettingModel.isShowCustomerBtn()
        const newService = []
        service.forEach(item => {
          // 默认开启
          item.enabled = true
          // 我的积分
          if (item.id === 'points') {
            item.name = '我的' + app.setting[SettingKeyEnum.POINTS.value].points_name
          }
          // 企业微信客服
          if (item.id === 'contact' && !isShowCustomerBtn) {
            item.enabled = false
          }
          // 数据角标
          if (item.count != undefined) {
            item.count = app.todoCounts[item.id]
          }
          newService.push(item)
        })
        app.service = filterModules(newService)
      },

      // 初始化订单操作数据
      initOrderTabbar() {
        const app = this
        const newOrderNavbar = []
        orderNavbar.forEach(item => {
          if (item.count != undefined) {
            item.count = app.todoCounts[item.id]
          }
          newOrderNavbar.push(item)
        })
        app.orderNavbar = newOrderNavbar
      },

      // 获取商城设置
      getSetting() {
        const app = this
        return new Promise((resolve, reject) => {
          SettingModel.data()
            .then(setting => {
              app.setting = setting
              resolve(setting)
            })
            .catch(reject)
        })
      },

      // 获取当前用户信息
      getUserInfo() {
        const app = this
        return new Promise((resolve, reject) => {
          !app.isLogin ? resolve(null) : UserApi.info({}, { load: app.isFirstload })
            .then(result => {
			  storage.set(USER_ID, result.data.id)
			  storage.set(NICK_NAME, result.data.nick_name)
			  storage.set(STATUS, result.data.status)
              app.userInfo = result.data
			  console.log('用户信息',result.data.status, storage.get(STATUS))
              resolve(app.userInfo)
            })
            .catch(err => {
              if (err.result && err.result.status == 401) {
                app.isLogin = false
                resolve(null)
              } else {
                reject(err)
              }
            })
        })
      },
	  // 转换时间戳
	  formatTime (data) {
		if(data) {
			const currTime = timestampChangDate('YYYY-mm-dd', data * 1000)
			return currTime
		} else {
			return ''
		}
	  },
	  
	  goDetails: function(id) {
		  this.$navTo('pages/user/privacyAgreement/index')
	  },
	  
	  // 关于我们
	  goAboutUsDetails() {
		  this.$navTo('pages/user/aboutUs')
	  },
	  
	  // 观看过的课程
	  goCourseRecord() {
		  this.$navTo('pages/user/courseRecord/index')
	  },
	  
	  // 作业管理
	  goHomeworkManage() {
		  if(!this.isLogin) {
			  homeworkApi.homeworkList({ page: 1 }, { load: false }).then(result => {})
		  } else {
			  if(this.get_expire_time(this.userInfo.status) > 0) {
			  	this.$navTo('pages/user/homework/index')
			  } else {
			  	this.$toast('会员权限已过期')
			  }
		  }
	  },
	  // 判断锁定时间
	  get_expire_time(val) {
	  	const date = new Date().getTime();
	  	if(val && val != '') {
	  		let time = val * 1000 - date
	  		console.log('时间1111',time,date)
	  		return time
	  	} else {
	  		return 0
	  	}
	  },
      // 跳转到登录页
      handleLogin() {
        !this.isLogin && this.$navTo('pages/login/index')
      },

      // 跳转到绑定手机号页面
      handleBindMobile() {
        this.$navTo('pages/user/bind/index')
      },

      // 跳转到修改个人信息页
      handlePersonal() {
        this.$navTo('pages/user/personal/index')
      },

      // 退出登录
      handleLogout() {
        const app = this
        uni.showModal({
          title: '友情提示',
          content: '您确定要退出登录吗?',
          success(res) {
            if (res.confirm) {
			  store.dispatch('LogoutWebsocket',{}) // 关闭websocket
              store.dispatch('Logout', {})
                .then(result => app.onRefreshPage())
            }
          }
        })
      },

      // 跳转到钱包页面
      onTargetWallet() {
        this.$navTo('pages/wallet/index')
      },

      // 跳转到订单页
      onTargetOrder(item) {
        this.$navTo('pages/order/index', { dataType: item.id })
      },

      // 跳转到我的积分页面
      onTargetPoints() {
        this.$navTo('pages/points/log')
      },

      // 跳转到我的优惠券页
      onTargetMyCoupon() {
        this.$navTo('pages/my-coupon/index')
      },

      // 跳转到服务页面
      handleService({ url }) {
        this.$navTo(url)
      },
      
	  // 图片地址拼接
	  getImgUrl(val) {
	      const url = ImgUrlPrefix(val)
	      return url
	  },
	  // 手机号中间四位数****代替
	  maskPhoneNumber(tel) {
		  tel = "" + tel;
		  var reg=/(\d{3})\d{4}(\d{4})/;
		  if(tel) {
			  var tel1 = tel.replace(reg, "$1****$2")
			  console.log(tel1)
			  return tel1
		  } else{
			  return ''
		  }
	  }
    },

    /**
     * 下拉刷新
     */
    onPullDownRefresh() {
      // 获取首页数据
      this.getPageData(() => {
        uni.stopPullDownRefresh()
      })
    },


  }
</script>

<style lang="scss" scoped>
  .container {
    padding-bottom: 60rpx;
  }

  // 页面头部
  .main-header {
    // background-color: #12a15c;
    position: relative;
    width: 100%;
    background-size: 100% 100%;
	height: 480rpx;
	.user-bg-item{
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 0;
	}
    .user-info {
      display: flex;
      // height: 100rpx;
	  padding: 50rpx 0rpx;
      position: absolute;
	  top: 140rpx;
	  left: 50rpx;
	  width: 88%;
	  z-index: 1;
      .user-avatar{
		 border-radius: 50%;
	  }
	  .user--avatar-item{
		  width: 100rpx;
		  height:100rpx;
	  }
      .user-content {
        display: flex;
        flex-direction: column;
        justify-content: center;
        color: #000; //#c59a46
		margin-left: 40rpx;

        .nick-name {
          font-size: 40rpx;
          font-weight: bold;
          max-width: 300rpx;
		  
        }
        .image-cc{
			width: 40rpx;
			height: 40rpx;
			margin-left: 20rpx;
		}
		.other--info{
			display: flex;
			justify-content: space-between;
		}
        .mobile {
          margin-top: 15rpx;
          font-size: 28rpx;
        }
		.identity{
			background-color: #c3e4d9;
			border-radius: 30rpx;
			padding: 8rpx 16rpx;
			font-size: 22rpx;
			margin-top: 20rpx;
		}
        .login-tips {
          margin-top: 12rpx;
          font-size: 30rpx;
        }

      }
    }
  }
 // 通栏卡片
 .i-card {
   background: #fff;
   padding: 24rpx 44rpx 24rpx 44rpx;
   width: 85%;
   // box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
   margin: 0 auto 20rpx auto;
   border-radius: 50rpx;
 }
 .user--list{
	 margin-top: 30rpx;
	 .user--item{
		 display: flex;
		 justify-content: space-between;
		 align-items: center;
		 color: #747474;
		 font-size: 30rpx;
		 .user-item-image{
			 width:46rpx;
			 height:46rpx;
			 vertical-align: bottom;
			 margin-right: 30rpx;
		 }
	 }
	 .user--icon-s{
		 color: #efefef;
	 }
 }
  // 角标组件
  .item-badge {
    position: absolute;
    top: 0;
    right: 55rpx;
    // background: $main-bg;
    background:#12a15c;// #fa2209;
    color: #fff;
    border-radius: 100%;
    min-width: 38rpx;
    height: 38rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rpx;
    font-size: 24rpx;
  }

  // 我的钱包
  .my-asset {
    display: flex;
    background: #fff;
    padding: 40rpx 0;

    .asset-right {
      width: 200rpx;
      border-left: 1rpx solid #eee;
    }

    .asset-right-item {
      text-align: center;
      color: #545454;

      .item-icon {
        font-size: 44rpx;
      }

      .item-name {
        margin-top: 14rpx;
        font-size: 28rpx;
      }

    }

    .asset-left-item {
      max-width: 183rpx;
      text-align: center;
      color: #666;
      padding: 0 16rpx;

      .item-value {
        font-size: 34rpx;
        color: $main-bg;
      }

      .item-name {
        margin-top: 14rpx;
        font-size: 28rpx;
      }

    }

  }

  // 订单操作
  .order-navbar {
    display: flex;
    margin: 20rpx auto 20rpx auto;
    padding: 20rpx 0 26rpx 0;
    width: 94%;
    box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
    font-size: 30rpx;
    border-radius: 5rpx;
    background: #fff;

    &-item {
      position: relative;
      width: 25%;

      .item-icon {
        text-align: center;
        margin: 0 auto;
        padding: 10rpx 0;
        color: #545454;
        font-size: 44rpx;
      }

      .item-name {
        font-size: 28rpx;
        color: #545454;
        text-align: center;
        margin-right: 10rpx;
      }

    }
  }

  // 我的服务
  .my-service {
    margin: 22rpx auto 22rpx auto;
    padding: 22rpx 0;
    width: 94%;
    box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
    border-radius: 5rpx;
    background: #fff;

    .service-title {
      padding-left: 24rpx;
      margin-bottom: 20rpx;
      font-size: 30rpx;
    }

    .service-content {

      margin-bottom: -20rpx;

      .service-item {
        position: relative;
        width: 25%;
        float: left;
        margin-bottom: 30rpx;

        .item-icon {
          text-align: center;
          margin: 0 auto;
          padding: 14rpx 0;
          color: $main-bg;
          font-size: 44rpx;
        }

        .item-name {
          font-size: 28rpx;
          color: #545454;
          text-align: center;
        }

      }
    }
  }

  // 退出登录
  .my-logout {
    display: flex;
    justify-content: center;
    margin-top: 50rpx;

    .logout-btn {
      width: 60%;
      margin: 0 auto;
      font-size: 28rpx;
      color: #616161;
      border-radius: 20rpx;
      border: 1px solid #dcdcdc;
      padding: 16rpx 0;
      text-align: center;
    }
  }

  // 绑定手机号 样式1
  .my-mobile {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16rpx 40rpx;
    background: #FCEBD1;

    .info {
      color: #cd8c0c;
      font-size: 28rpx;
    }

    .btn-bind {
      padding: 8rpx 24rpx;
      background-color: #EAB766;
      color: #fff;
      border-radius: 30rpx;
      font-size: 26rpx;
      text-align: center;
    }
  }

  // 绑定手机号 样式2
  .my-mobile2 {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20rpx auto 20rpx auto;
    padding: 12rpx 40rpx;
    width: 94%;
    box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
    font-size: 30rpx;
    border-radius: 5rpx;
    background: #fff;

    .info {
      // color: #cd8c0c;
      font-size: 26rpx;
    }

    .btn-bind {
      padding: 8rpx 24rpx;
      background-color: #EAB766;
      color: #fff;
      border-radius: 30rpx;
      font-size: 26rpx;
      text-align: center;
    }
  }
</style>